import 'dart:convert';

import 'package:flutter_study/project/_01osc/constants/constants.dart'
    show AppUrls, AppInfos;
import 'package:flutter_study/project/_01osc/utils/data_utils.dart';
import 'package:flutter_study/project/_01osc/utils/net_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class LoginWebPage extends StatefulWidget {
  @override
  _LoginWebPageState createState() => _LoginWebPageState();
}

class _LoginWebPageState extends State<LoginWebPage> {
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();

  // 是否正在加载
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    // 监听url变化
    flutterWebviewPlugin.onUrlChanged.listen((event) {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
      if (event != null && event.length > 0 && event.contains('?code=')) {
        // 截取code，请求token
        String code = event.split('?')[1].split('&')[0].split('=')[1];
        Map<String, dynamic> params = Map<String, dynamic>();
        params['client_id'] = AppInfos.CLIENT_ID;
        params['client_secret'] = AppInfos.CLIENT_SECRET;
        params['grant_type'] = 'authorization_code';
        params['redirect_uri'] = AppInfos.REDIRECT_URI;
        params['code'] = '$code';
        params['dataType'] = 'json';
        NetUtils.get(AppUrls.OAUTH2_TOKEN, params).then((value) {
          // 解析数据
          if (value != null) {
            Map<String, dynamic> res = json.decode(value);
            if (res != null && res.isNotEmpty) {
              // 登录成功，获取到token
              DataUtils.saveLoginInfo(res);
              // 退出页面，并发送刷新消息
              Navigator.pop(context, 'refresh');
            }
          }
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    flutterWebviewPlugin.close();
  }

  List<Widget> _buildAppBarChildren() {
    List<Widget> children = [Text('开源中国登录')];
    if (isLoading) {
      children.add(SizedBox(
        width: 10.0,
      ));
      // loading
      children.add(CupertinoActivityIndicator());
    }
    return children;
  }

  @override
  Widget build(BuildContext context) {
    String url = AppUrls.OAUTH2_AUTHORIZE +
        '?response_type=code&client_id=' +
        AppInfos.CLIENT_ID +
        '&redirect_uri=' +
        AppInfos.REDIRECT_URI;
    return WebviewScaffold(
      url: url,
      appBar: AppBar(
        title: Row(
          children: _buildAppBarChildren(),
        ),
      ),
      withJavascript: true,
      // 缓存
      withLocalStorage: true,
      withZoom: true,
    );
  }
}
